//
//  FastTaskManager.m
//  gdemm
//
//  Created by 乔明超 on 16/4/1.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "FastTaskManager.h"
#import "VPNManager.h"
#import "GeoFencing.h"
#import "WaterMarkPolicyManager.h"
#import "WbAuditManager.h"
#import "CallLimit.h"
@interface FastTaskManager()
@property (nonatomic,strong) NSMutableArray *mFastTasks;
@property (nonatomic,strong) NSMutableArray *delays;

@end
@implementation FastTaskManager
static FastTaskManager *_mInstance;
- (NSMutableArray *)mFastTasks{

    if (_mFastTasks == nil) {
        _mFastTasks = [NSMutableArray array];
    }
    return _mFastTasks;
}

- (NSMutableArray *)delays{

    if (_delays == nil) {
        _delays = [NSMutableArray array];
    }
    
    return _delays;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self addFastTasks];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self fastTaskThread];
            
        });
        
    }
    return self;
}
+ (instancetype)getInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _mInstance = [[self alloc]init];
    });
    return _mInstance;
}

- (void)fastTaskThread{
    NSInteger time = 0;
    [NSThread sleepForTimeInterval:5.0];
    while (YES) {
        for (int i = 0; i < self.mFastTasks.count; i++) {
            if (time % [self.delays[i] intValue] == 0) {
                if ([self.mFastTasks[i] valid]) {
                    [self.mFastTasks[i] run];
                    
                }
                
            }
        }
        
        [NSThread sleepForTimeInterval:0.1];
        time += 100;
    }
    
}

- (BOOL)addFastTaskWithFastTast:(id<FastTask>)task withDelay:(NSInteger)delay{
    
    if ([self.mFastTasks indexOfObject:task] != NSNotFound) {
        return NO;
        
    }
    [self.mFastTasks addObject:task];
    [self.delays addObject:[NSNumber numberWithInteger:delay]];
    
    return YES;
}

- (void)addFastTasks{
    [self addFastTaskWithFastTast:[VPNManager getInstance] withDelay:30000];
    [self addFastTaskWithFastTast:[GeoFencing getInstance] withDelay:10000];
    [self addFastTaskWithFastTast:[WaterMarkPolicyManager getInstence] withDelay:5000];
    [self addFastTaskWithFastTast:[WbAuditManager getInstance] withDelay:8000];
     [self addFastTaskWithFastTast:[CallLimit getInstance] withDelay:30000];
}
@end
